package com.cbnu.SmartCampusLife;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

@SuppressLint("WorldReadableFiles")
public class Estudent extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
	
	private ImageView stuFaceIV;
	private ImageView stuBarcodeIV;
	private String path = "/data/data/com.cbnu.SmartCampusLife/files/";
	
	private static final int PICK_FROM_CAMERA = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	
	private Uri uri;
	
	private static  int ivid;
	private int width;
	
	private LinearLayout ll;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_estudent);
        ll = (LinearLayout)findViewById(R.id.e_stull);
        
        //Get Resolution of Display, for Cropping Picture.
        Display dis = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        width = dis.getWidth();
        
        TextView stuId = (TextView)findViewById(R.id.e_stuid);
        TextView stuName = (TextView)findViewById(R.id.e_stuname);
        TextView stuPart = (TextView)findViewById(R.id.e_stupart);
        stuFaceIV = (ImageView)findViewById(R.id.e_stuface);
        stuBarcodeIV = (ImageView)findViewById(R.id.e_barcode);
        
        File chk = new File(path + "stuFace.jpg");
        if(chk.isFile()) {
        	Bitmap struFaceBMP = BitmapFactory.decodeFile(path + "stuFace.jpg");
        	stuFaceIV.setImageBitmap(struFaceBMP);
        }
        chk = new File(path + "stuBarcode.jpg");
        if(chk.isFile()) {
        	Bitmap struBarcodeBMP = BitmapFactory.decodeFile(path + "stuBarcode.jpg");
        	stuBarcodeIV.setImageBitmap(struBarcodeBMP);
        }
        try {
        	FileInputStream fis = openFileInput("stu_id.txt");
        	BufferedInputStream bis = new BufferedInputStream(fis);
    		BufferedReader br = new BufferedReader(new InputStreamReader(bis));
    		String text = br.readLine();
    		stuId.setText(text);
        } catch(Exception e) { e.printStackTrace(); }
        
        try {
        	FileInputStream fis = openFileInput("stu_name.txt");
        	BufferedInputStream bis = new BufferedInputStream(fis);
    		BufferedReader br = new BufferedReader(new InputStreamReader(bis));
    		stuName.setText(br.readLine());
        } catch(Exception e) { e.printStackTrace(); }
        
        try {
        	FileInputStream fis = openFileInput("stu_part.txt");
        	BufferedInputStream bis = new BufferedInputStream(fis);
    		BufferedReader br = new BufferedReader(new InputStreamReader(bis));
    		stuPart.setText(br.readLine());
        } catch(Exception e) { e.printStackTrace(); }
        
        stuFaceIV.setClickable(true);
        stuFaceIV.setOnClickListener(this);
        stuBarcodeIV.setClickable(true);
        stuBarcodeIV.setOnClickListener(this);
    }
	
	public void onClick(View v) {
		final ImageView iv = (ImageView)v;
		ivid = iv.getId();
		DialogInterface.OnClickListener cameraListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				doTakePhotoAction();
			}
		};
		DialogInterface.OnClickListener albumListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				doTakeAlbumAction();
			}
		};

		new AlertDialog.Builder(this).setTitle("사진 선택")
				.setMessage("촬영하거나 앨범에서 선택해 주세요. 단, 촬영할 경우 기본 '카메라'를 이용해 주세요.")
				.setPositiveButton("촬영", cameraListener)
				.setNeutralButton("앨범", albumListener)
				.show();
	}
	

	private void doTakePhotoAction() {
		/*
		 * 참고 해볼곳 http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo
		 * http://stackoverflow
		 * .com/questions/1050297/how-to-get-the-url-of-the-captured-image
		 * http://www.damonkohler.com/2009/02/android-recipes.html
		 * http://www.firstclown.us/tag/android/
		 */
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// 임시로 사용할 파일의 경로를 생성
		String url = "tmp_" + String.valueOf(System.currentTimeMillis())
				+ ".jpg";
		uri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), url));

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, 	uri);
//		// 특정기기에서 사진을 저장못하는 문제가 있어 다음을 주석처리 합니다.
//		intent.putExtra("return-data", true);
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}

	/**
	 * 앨범에서 이미지 가져오기
	 */
	private void doTakeAlbumAction() {
		// 앨범 호출
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case CROP_FROM_CAMERA: {
			// 크롭이 된 이후의 이미지를 넘겨 받습니다.
			// 이미지뷰에 이미지를 보여준다거나 부가적인 작업 이후에
			// 임시 파일을 삭제합니다.
			final Bundle extras = data.getExtras();

			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
//				mPhotoImageView.setImageBitmap(photo);
				if(ivid == R.id.e_stuface) {
					stuFaceIV.setImageBitmap(photo);
					stuFaceIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
					try {
						FileOutputStream fos;
						fos = openFileOutput("stuFace.jpg", Context.MODE_WORLD_READABLE);
						photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				else if(ivid == R.id.e_barcode) {
					stuBarcodeIV.setImageBitmap(photo);
					stuBarcodeIV.setScaleType(ImageView.ScaleType.FIT_CENTER);
					try {
						FileOutputStream fos;
						fos = openFileOutput("stuBarcode.jpg", Context.MODE_WORLD_READABLE);
						photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			// 임시 파일 삭제
			File f = new File(uri.getPath());
			if (f.exists()) {
				f.delete();
			}

			break;
		}

		case PICK_FROM_ALBUM: {
			// 이후의 처리가 카메라와 같으므로 일단 break 없이 진행합니다.
			// 실제 코드에서는 좀더 합리적인 방법을 선택하시기 바랍니다.
			uri = data.getData();
		}

		case PICK_FROM_CAMERA: {
			// 이미지를 가져온 이후의 리사이즈할 이미지 크기를 결정합니다.
			// 이후에 이미지 크롭 어플리케이션을 호출하게 됩니다.
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, "image/*");
			try {
				if(ivid == R.id.e_stuface) {
					intent.putExtra("outputX", 150);
					intent.putExtra("outputY", 150);
					intent.putExtra("aspectX", 1);
					intent.putExtra("aspectY", 1);
				}
				else if(ivid == R.id.e_barcode) {
					intent.putExtra("outputX", width);
					intent.putExtra("outputY", width/4);
					intent.putExtra("aspectX", 4);
					intent.putExtra("aspectY", 1);
				}
				intent.putExtra("scale", true);
				intent.putExtra("return-data", true);
				startActivityForResult(intent, CROP_FROM_CAMERA);
			} catch(Exception e) { e.printStackTrace(); }
		}
		}
	}
	
	//After first run, FlipView can show TimeTable thumbnail.
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		Thread takeScreenShot = new TakeScreenShot("eStudent.jpg", ll, Estudent.this);
        takeScreenShot.start();
	}
}